package com.easy.controller;

import com.easy.bean.User;
import com.easy.service.IUserService;
import com.easy.util.LayData;
import com.easy.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    IUserService userService;

    @RequestMapping("getuserinfo")
    @ResponseBody
    public LayData getLoginUser(HttpSession session){
        User loginuser=(User)session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        if(loginuser==null){
            throw new RuntimeException("未登录");
        }
        int id=loginuser.getId();
        User user=userService.getUserByID(id);
        return LayData.success(200,"",user);
    }
    @RequestMapping("edit")
    @ResponseBody
    public LayData editUser(HttpSession session,User user){
        if(user.getId()==0){
            User loginuser=(User)session.getAttribute(SYS.SHOPPING_LOGIN_USER);
            int id=loginuser.getId();
            user.setId(id);
        }
        userService.editUser(user);
        return LayData.success(200,null);
    }
    @RequestMapping("getuserbyusername")
    @ResponseBody
    public LayData getUserByUsername(User user){
        User userData=userService.getUser(user);
        return LayData.success(userData);
    }
    @RequestMapping("register")
    @ResponseBody
    public LayData register(User user,String confirmpassword){

        //验证格式是否正确
        boolean check=SYS.check("^\\w{6,16}$",user.getUsername(),user.getPassword(),confirmpassword);
        if(!check){
            return LayData.success(400,"输入的内容格式不正确");
        }
        if(!confirmpassword.equals(user.getPassword())){
            return LayData.success(400,"两次输入的密码不一样");
        }
        User userData=userService.getUser(user);
        if(userData!=null){
            return LayData.success(400,"账号已经存在");
        }
        String hexpass=SYS.digest(user.getPassword());
        user.setPassword(hexpass);
        int count=userService.add(user);
        return LayData.success(200,"注册成功",userData);
    }
}
